<template>
  <div id="app">
    <div class="chat-container">
      <!-- 会话列表 -->
      <div class="session-list">
        <div
            v-for="(session, index) in sessions"
            :key="index"
            class="session-item"
            :class="{ active: activeSessionIndex === index }"
            @click="selectSession(index)"
        >
          <span class="session-status" :class="{ online: session.isConnected, offline:!session.isConnected }"></span>
          <span class="session-status-text">{{ session.isConnected ? '在线' : '离线' }}</span>
          <span class="session-name">{{ session.title }}</span>
          <!-- 三个小点按钮 -->
          <div v-if="!session.talkInfoId.toString().startsWith('temp-')" class="session-actions-trigger" @click.stop="toggleActionsMenu(index)">
            <span>...</span>
          </div>
          <!-- 编辑和删除操作菜单 -->
          <div
              v-if="session.showActionsMenu"
              class="session-actions-menu"
              @click.stop
          >
            <button @click="openEditModal(index)">编辑</button>
            <button @click="openDeleteModal(index)">删除</button>
          </div>
        </div>
        <button @click="createNewSession" class="new-session-button" :disabled="hasUnconnectedSession">
          新建会话
        </button>
      </div>
      <!-- 聊天内容 -->
      <div class="chat-content">
        <div class="chatBox">
          <!-- 错误提示 -->
          <div v-if="errorMessage" class="error-message">
            {{ errorMessage }}
          </div>
          <!-- 聊天消息显示区域 -->
          <div class="chat-messages">
            <div v-for="(message, index) in currentMessages" :key="index" class="message">
              <!-- 用户消息 -->
              <div v-if="message.sender === 'user'" class="user-message-container">
                <article class="message-content user-message">{{ message.text }}</article>
              </div>
              <!-- 机器人消息 -->
              <div v-else class="bot-message-container">
                <article class="message-content bot-message" v-html="renderMarkdown(message.text)"></article>
              </div>
            </div>
          </div>
          <!-- 输入框和发送按钮 -->
          <div class="chat-input">
            <textarea
                v-model="inputMessage"
                placeholder="请输入你的问题..."
                @keyup="handleKeyup"
                rows="6"
                :disabled="!isConnected"
            />
            <button @click="handleButtonClick" :disabled="!isConnected">
              {{ currentSession.isGenerating ? '停止生成' : '发送' }}
            </button>
          </div>
        </div>
      </div>
    </div>
    <!-- 编辑模态框 -->
    <MyModal :visible="isEditModalVisible" title="编辑会话标题" @close="closeEditModal">
      <input v-model="editTitle" placeholder="请输入新的会话标题" />
      <template #footer>
        <button @click="closeEditModal">取消</button>
        <button @click="confirmEdit">确定</button>
      </template>
    </MyModal>
    <!-- 删除模态框 -->
    <MyModal :visible="isDeleteModalVisible" title="确认删除" @close="closeDeleteModal">
      <p>确定要删除该会话吗？</p>
      <template #footer>
        <button @click="closeDeleteModal">取消</button>
        <button @click="confirmDelete">确定</button>
      </template>
    </MyModal>
  </div>
</template>

<script setup>
import {computed, onMounted, onUnmounted, reactive, ref} from 'vue';
import MyModal from './MyModal.vue';
import {marked} from 'marked';
import DOMPurify from 'dompurify';
import axios from 'axios';

// 配置 marked（保持不变）
marked.setOptions({
  gfm: true,
  breaks: true,
  highlight: function (code) {
    return code;
  }
});

// 渲染 Markdown 内容（保持不变）
const renderMarkdown = (content) => {
  console.log("渲染前内容",content);
  content = content.replace(/<think>/g, '<div><span class="deepThink">');
  if (!content.includes('</think>')) {
    content = content.concat('</span></div>');
  }
  if (content.includes('</think>')) {
    content = content.replace(/<\/span><\/div>/g, '');
    content = content.replace(/<\/think>/g, '</span></div>');
  }
  const html = marked(content);
  const sanitizedHtml = DOMPurify.sanitize(html);
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = sanitizedHtml.toString();
  const deepThinkElements = tempDiv.querySelectorAll('.deepThink');

  deepThinkElements.forEach((element) => {
    if (element.textContent.trim() === '') {
      element.textContent = '暂无推理过程';
    }
  });
  console.log("渲染后内容",tempDiv.innerHTML);
  return tempDiv.innerHTML;
};

// 存储所有会话（改为空数组）
const sessions = ref([]);

// 当前激活的会话索引
const activeSessionIndex = ref(0);

// 新增：统一错误处理函数
const handleNetworkError = (error, session) => {
  let errorMsg = '服务暂时不可用，请稍后重试';
  if (!navigator.onLine) {
    errorMsg = '网络连接已断开，请检查网络设置';
  } else if (error.message === 'Network Error') {
    errorMsg = '无法连接到服务器，请确认后端服务已启动';
  } else if (error.response?.status >= 500) {
    errorMsg = '服务器内部错误，请联系管理员';
  }
  session.errorMessage = errorMsg;
  setTimeout(() => {
    session.errorMessage = ''; // 5秒后自动清除错误
  }, 5000);
};


// 发送消息函数
const sendMessage = () => {
  if (!inputMessage.value) return;
  const messageData = JSON.stringify({
    talkInfoId: currentSession.value?.talkInfoId,
    content: inputMessage.value+'\n'
  });
  currentMessages.value.push({ sender: 'user', text: inputMessage.value });
  currentSession.value.socket.send(messageData);
  // 保存用户消息到数据库
  if (!currentSession.value.talkInfoId.toString().startsWith('temp-')){
    saveUserMessageToDatabase(currentSession.value.talkInfoId, inputMessage.value,'user');
  }
  inputMessage.value = '';
  currentSession.value.isGenerating = true;
};

// 停止生成函数
const stopGenerating = () => {
  const messageData = JSON.stringify({
    talkInfoId: currentSession.value?.talkInfoId,
    content: 'stopSending'
  });
  currentSession.value.socket.send(messageData);
  currentSession.value.isGenerating = false;
};

// 发送按钮点击处理
const handleButtonClick = () => {
  currentSession.value.isGenerating ? stopGenerating() : sendMessage();
};

// 键盘事件处理
const handleKeyup = (event) => {
  if (event.key === 'Enter' &&!event.shiftKey) sendMessage();
};

// 保存用户消息到数据库
const saveUserMessageToDatabase = async (talkInfoId, message,messageType) => {
  try {
    await axios.post('/api/deepSeek/saveTalkInfoMessage', {
      talkInfoId,
      message,
      messageType
    });
  } catch (error) {
    console.error('保存用户消息到数据库失败:', error);
    const errorSession = sessions.value[activeSessionIndex.value] || {};
    handleNetworkError(error, errorSession);
  }
};

// 保存机器人消息到数据库
const saveBotMessageToDatabase = async (talkInfoId, message,messageType) => {
  try {
    await axios.post('/api/deepSeek/saveTalkInfoMessage', {
      talkInfoId,
      message,
      messageType
    });
  } catch (error) {
    console.error('保存机器人消息到数据库失败:', error);
    const errorSession = sessions.value[activeSessionIndex.value] || {};
    handleNetworkError(error, errorSession);
  }
};

// 获取单个会话框的历史消息列表
const getMessageListByTalkInfoId = async (talkInfoId) => {
  try {
    const response = await axios.get('/api/deepSeek/getMessageListByTalkInfoId', {
      params: { talkInfoId }
    });
    // 检查 response.data.data 是否存在且为数组
    if (Array.isArray(response.data?.data)) {
      //构建数据
      const result = response.data.data.map(item => {
        return {
          sender: item.messageType,
          text: item.message
        };
      });
      console.log('构建数据成功+++:', result)
      return result;
    }
    return [];
  } catch (error) {
    console.error('获取会话消息列表失败:', error);
    const errorSession = sessions.value[activeSessionIndex.value] || {};
    handleNetworkError(error, errorSession);
    return [];
  }
};

//页面刷新时初始化会话列表
const fetchSessions = async () => {
  try {
    const response = await axios.get('/api/deepSeek/talkInfoList');
    const data = response.data?.data || [];

    // 创建临时会话
    const tempSession = reactive({
      talkInfoId: 'temp-' + Date.now(),
      title: '临时会话',
      messages: [{ sender: 'bot', text: '欢迎使用临时对话框！有什么可以帮助你的?' }],
      inputMessage: '',
      errorMessage: '',
      isConnected: false,
      isGenerating: false,
      socket: null,
      reconnectInterval: null,
      retryCount: 0, // 新增重试次数
      currentBotMessage: '' // 用于存储当前机器人流式响应消息
    });

    // 初始化会话列表，将临时会话添加到列表开头
    sessions.value = [tempSession, ...data.map(item =>
        reactive({
          talkInfoId: item.id,
          title: item.title || `会话 ${sessions.value.length + 1}`,
          messages: [{ sender: 'bot', text: '欢迎使用！有什么可以帮助你的?' }],
          inputMessage: '',
          errorMessage: '',
          isConnected: false,
          isGenerating: false,
          socket: null,
          reconnectInterval: null,
          retryCount: 0, // 新增重试次数
          currentBotMessage: '' // 用于存储当前机器人流式响应消息
        })
    )];
    // 为每个会话获取对话消息
    for (const session of sessions.value) {
      const talkInfoId = session?.talkInfoId;
      const result = talkInfoId.toString().startsWith('temp-')
      if (!result){
        const messages = await getMessageListByTalkInfoId(session?.talkInfoId);
        console.log("获取的消息为：",messages);
        session.messages = messages && messages.length > 0 ? messages :[{ sender: 'bot', text: '欢迎使用！有什么可以帮助你的?' }];
      }
    }

    // 若查询到会话框列表，开始逐一连接
    if (data.length > 0) {
      sessions.value.forEach(session => {
        reconnectWebSocket(session);
      });
    } else {
      // 查不到则直接连接临时会话框
      reconnectWebSocket(tempSession);
    }
  } catch (error) {
    console.error('获取会话列表失败:', error);
    // 创建临时会话
    const tempSession = reactive({
      talkInfoId: 'temp-' + Date.now(),
      title: '临时会话',
      messages: [{ sender: 'bot', text: '欢迎使用！' }],
      inputMessage: '',
      errorMessage: '',
      isConnected: false,
      isGenerating: false,
      socket: null,
      reconnectInterval: null,
      retryCount: 0, // 新增重试次数
      currentBotMessage: '' // 用于存储当前机器人流式响应消息
    });
    sessions.value = [tempSession];
    activeSessionIndex.value = 0;
    handleNetworkError(error, tempSession);
    // 直接连接临时会话框
    reconnectWebSocket(tempSession);
  }
};

// 计算属性（保持不变）
const currentMessages = computed(() => sessions.value[activeSessionIndex.value]?.messages || []);
const inputMessage = computed({
  get: () => sessions.value[activeSessionIndex.value]?.inputMessage || '',
  set: (value) => (sessions.value[activeSessionIndex.value].inputMessage = value)
});
const errorMessage = computed({
  get: () => sessions.value[activeSessionIndex.value]?.errorMessage || '',
  set: (value) => (sessions.value[activeSessionIndex.value].errorMessage = value)
});
const isConnected = computed({
  get: () => sessions.value[activeSessionIndex.value]?.isConnected || false,
  set: (value) => (sessions.value[activeSessionIndex.value].isConnected = value)
});
const currentSession = computed(() => sessions.value[activeSessionIndex.value] || {});

// WebSocket 连接管理（修改）
let fetchSessionsDebounceTimer = null;
const reconnectWebSocket = (session) => {
  if (session.reconnectInterval) clearInterval(session.reconnectInterval);

  const initialDelay = 3000; // 初始延迟时间
  const maxDelay = 60000; // 最大延迟时间
  const backoffFactor = 2; // 退避因子

  const attemptReconnect = () => {
    if (!session.socket || session.socket.readyState === WebSocket.CLOSED) {
      session.socket = new WebSocket(`ws://localhost:8085/websocket?talkInfoId=${session.talkInfoId}`);

      session.socket.onopen = () => {
        session.errorMessage = '';
        session.isConnected = true;
        session.retryCount = 0; // 连接成功，重置重试次数
        clearInterval(session.reconnectInterval);
      };

      session.socket.onmessage = (event) => {
        const targetSession = sessions.value.find(s => s?.socket === session.socket);
        if (!targetSession) return;

        if (event.data.includes('[END_OF_MESSAGE_GENERATE]')) {
          targetSession.isGenerating = false;
          // 保存机器人消息到数据库
          if (!targetSession?.talkInfoId.toString().startsWith('temp-')){
            saveBotMessageToDatabase(targetSession?.talkInfoId, targetSession.currentBotMessage,'bot');
          }
          targetSession.currentBotMessage = '';
          return;
        }

        targetSession.currentBotMessage += event.data;
        const lastMessage = targetSession?.messages[targetSession?.messages.length - 1];
        lastMessage?.sender === 'bot'
            ? lastMessage.text += event.data
            : targetSession?.messages.push({ sender: 'bot', text: event.data });
      };

      session.socket.onerror = (error) => {
        console.error('连接错误:', error);
        handleNetworkError(error, session);
        session.isConnected = false;
        session.retryCount++;
        const nextDelay = Math.min(initialDelay * Math.pow(backoffFactor, session.retryCount), maxDelay);
        session.reconnectInterval = setTimeout(attemptReconnect, nextDelay);
      };

      session.socket.onclose = () => {
        handleNetworkError(new Error('连接意外关闭'), session);
        session.isConnected = false;
        session.retryCount++;
        const nextDelay = Math.min(initialDelay * Math.pow(backoffFactor, session.retryCount), maxDelay);
        session.reconnectInterval = setTimeout(attemptReconnect, nextDelay);
        // 尝试刷新会话列表，添加防抖机制
        if (fetchSessionsDebounceTimer) {
          clearTimeout(fetchSessionsDebounceTimer);
        }
        fetchSessionsDebounceTimer = setTimeout(() => {
          fetchSessions();
        }, 3000); // 3 秒防抖
      };
    }
  };
  attemptReconnect();
};

// 创建新会话
const createNewSession = async () => {
  if (hasUnconnectedSession.value) return;
  try {
    // 新建新会话的同时保存到后台
    const response = await axios.post('/api/deepSeek/saveTalkInfo', {
      title: `历史会话 ${sessions.value.length}`
    });

    const newSession = reactive({
      talkInfoId: response.data.data,
      title: `历史会话 ${sessions.value.length}`,
      messages: [{ sender: 'bot', text: '欢迎使用！有什么可以帮助你的?' }],
      inputMessage: '',
      errorMessage: '',
      isConnected: false,
      isGenerating: false,
      socket: null,
      reconnectInterval: null,
      retryCount: 0, // 新增重试次数
      currentBotMessage: '' // 用于存储当前机器人流式响应消息
    });

    sessions.value.push(newSession);
    activeSessionIndex.value = sessions.value.length - 1;
    reconnectWebSocket(newSession);
  } catch (error) {
    console.error('创建会话失败:', error);
    const errorSession = sessions.value[activeSessionIndex.value] || {};
    handleNetworkError(error, errorSession);

    // 确保至少存在一个会话
    if (sessions.value.length === 0) {
      const tempSession = reactive({
        talkInfoId: 'temp-' + Date.now(),
        title: '临时会话',
        messages: [{ sender: 'bot', text: '欢迎使用！' }],
        inputMessage: '',
        errorMessage: '',
        isConnected: false,
        isGenerating: false,
        socket: null,
        reconnectInterval: null,
        retryCount: 0, // 新增重试次数
        currentBotMessage: '' // 用于存储当前机器人流式响应消息
      });
      sessions.value = [tempSession];
      activeSessionIndex.value = 0;
    }
  }
};

// 切换操作菜单显示隐藏
const toggleActionsMenu = (index) => {
  sessions.value.forEach((session, i) => {
    session.showActionsMenu = i === index && !session.showActionsMenu;
  });
};
//============================编辑和删除会话框相关操作逻辑=========================================================================
const isEditModalVisible = ref(false);
const isDeleteModalVisible = ref(false);
const editTitle = ref('');
const deleteTitle = ref('');
let currentEditIndex = -1;
let currentDeleteIndex = -1;

const openEditModal = (index) => {
  currentEditIndex = index;
  editTitle.value = sessions.value[index].title;
  isEditModalVisible.value = true;
};

const closeEditModal = () => {
  isEditModalVisible.value = false;
};

const confirmEdit = async () => {
  const session = sessions.value[currentEditIndex];
  if (editTitle.value && editTitle.value!== session.title) {
    try {
      await axios.post('/api/deepSeek/updateTalkInfo', {
        id: session.talkInfoId,
        title: editTitle.value
      });
      session.title = editTitle.value;
    } catch (error) {
      console.error('编辑会话失败:', error);
      handleNetworkError(error, session);
    }
  }
  closeEditModal();
};

const openDeleteModal = (index) => {
  currentDeleteIndex = index;
  deleteTitle.value = sessions.value[index].title;
  isDeleteModalVisible.value = true;
};

const closeDeleteModal = () => {
  isDeleteModalVisible.value = false;
};

const confirmDelete = async () => {
  const session = sessions.value[currentDeleteIndex];
  if (session.talkInfoId.toString().startsWith('temp-')) {
    console.log('临时会话不能删除');
    closeDeleteModal();
    return;
  }
  try {
    await axios.post('/api/deepSeek/deleteTalkInfo', {
      id: session.talkInfoId
    });
    sessions.value.splice(currentDeleteIndex, 1);
    if (activeSessionIndex.value === currentDeleteIndex) {
      activeSessionIndex.value = Math.max(0, activeSessionIndex.value - 1);
    }
  } catch (error) {
    console.error('删除会话失败:', error);
    handleNetworkError(error, session);
  }
  closeDeleteModal();
};
//======================================================================================================================
// 选择会话
const selectSession = (index) => {
  activeSessionIndex.value = index;
  isConnected.value = sessions.value[index].isConnected;
};

// 计算属性：判断是否有未连接的会话
const hasUnconnectedSession = computed(() => {
  return sessions.value.some(session =>!session?.isConnected);
});

// 生命周期
let serviceCheckInterval;
onMounted(() => {
  fetchSessions(); // 初始化时获取会话列表
  
  // 添加全局点击事件监听器
  document.addEventListener('click', () => {
    sessions.value.forEach(session => {
      session.showActionsMenu = false;
    });
  });
  
  // 定期检查后端服务可用性
  serviceCheckInterval = setInterval(() => {
    axios.get('/api/deepSeek/heartBeatCheck')
        .then(() => {
          // 服务可用，对未连接的会话进行重试
          sessions.value.forEach(session => {
            if (!session?.isConnected) {
              reconnectWebSocket(session);
            }
          });
        })
        .catch(error => {
          console.error('后端服务不可用:', error);
          sessions.value.forEach(session => {
            session.isConnected = false;
            if (session?.socket) {
              session.socket.close();
            }
          });
        });
  }, 10000); // 每10秒检查一次
});

onUnmounted(() => {
  sessions.value.forEach((session) => {
    if (session?.socket) session.socket.close();
    if (session?.reconnectInterval) clearInterval(session.reconnectInterval);
  });
  clearInterval(serviceCheckInterval);
  
  // 移除全局点击事件监听器
  document.removeEventListener('click', () => {
    sessions.value.forEach(session => {
      session.showActionsMenu = false;
    });
  });
});
</script>

<style scoped>
#app {
  display: flex;
  height: 100vh;
  margin: 0;
  padding: 0;
  background-color: #f9f9f9; /* 更柔和的背景色 */
}

/* 新增错误提示样式 */
.error-message {
  background: #ffebee;
  color: #b71c1c;
  padding: 12px;
  margin: 16px;
  border-radius: 8px;
  border: 1px solid #ffcdd2;
  display: flex;
  align-items: center;
  gap: 8px;
}

.error-message::before {
  content: "⚠️";
  font-size: 1.2em;
}

.chat-container {
  display: flex;
  width: 100%;
  height: 100%;
  border: 1px solid #e0e0e0;
  border-radius: 10px;
  overflow: hidden;
  background-color: white;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}

.session-list {
  width: 15%; /* 将会话列表宽度调小 */
  height: 100%;
  border-right: 1px solid #e0e0e0;
  padding: 15px;
  box-sizing: border-box;
  overflow-y: auto;
  background-color: #f5f5f5; /* 会话列表背景色 */
}

.session-item {
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  margin-bottom: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.3s ease;
  position: relative;  /* 添加相对定位 */
}

.session-item:hover {
  background-color: #e8f6f8;
  transform: scale(1.02); /* 鼠标悬停时放大 */
}

.session-item.active {
  background-color: #d8eafd;
  border-color: #73a6ff;
}

.session-status {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.3); /* 状态点添加阴影 */
}

.online {
  background-color: #28a745;
}

.offline {
  background-color: #dc3545;
}

.session-status-text {
  color: #666;
  font-size: 0.9em;
}

.session-name {
  flex: 1;
  color: #333;
}

.new-session-button {
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  width: 100%;
  transition: background-color 0.3s ease; /* 按钮背景色过渡动画 */
}

.new-session-button:hover {
  background-color: #0056b3;
}

.chat-content {
  width: 85%; /* 相应增大聊天内容区域宽度 */
  height: 100%;
  padding: 15px;
  box-sizing: border-box;
}

.chatBox {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  border: 1px solid #e0e0e0;
  border-radius: 10px;
  overflow: hidden;
  background-color: white;
}

.error-message {
  background-color: #f8d7da;
  color: #721c24;
  padding: 12px;
  margin-bottom: 12px;
  border-radius: 8px;
  text-align: center;
  animation: fadeIn 0.3s ease; /* 错误提示淡入动画 */
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.chat-messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  overflow-x: auto;
}

.message {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
  animation: slideIn 0.3s ease; /* 消息滑入动画 */
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(-10px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.user-message-container {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

.bot-message-container {
  display: flex;
  justify-content: flex-start;
  width: 100%;
  gap: 12px;
}

.user-message,
.bot-message {
  background-color: #ffffff;
  padding: 10px;
  border-radius: 8px;
  width: auto;
  white-space: pre-wrap; /* 保留空白符序列，但是正常地进行换行 */
  word-wrap: break-word; /* 允许长单词或 URL 地址换行到下一行 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  max-width: 100%;
}

.message-content {
  max-width: 100%;
  overflow-x: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
  word-break: break-all;
  font-family: monospace;
  padding: 12px;
  background: #f8f8f8;
  border-radius: 4px;
}

/* 针对代码块的特殊处理 */
.message-content code {
  display: block;
  padding: 10px;
  background: #282c34;
  color: #abb2bf;
  border-radius: 4px;
  margin: 8px 0;
  overflow-x: auto;
}

/* 小屏幕设备（如手机） */
@media (max-width: 767px) {
  .message-content {
    font-size: 14px;
  }
  .message-content code {
    font-size: 12px;
  }
}

/* 中等屏幕设备（如平板） */
@media (min-width: 768px) and (max-width: 991px) {
  .message-content {
    font-size: 16px;
  }
  .message-content code {
    font-size: 14px;
  }
}

/* 大屏幕设备（如桌面电脑） */
@media (min-width: 992px) {
  .message-content {
    font-size: 16px;
  }
  .message-content code {
    font-size: 16px;
  }
}

/* 保持聊天消息容器允许滚动 */
.chat-messages {
  overflow-x: hidden;
  overflow-y: auto;
}

.user-message {
  background-color: #e8f6f8;
  margin-right: 12px;
}

.bot-message {
  background-color: #f0f0f0;
  margin-left: 12px;
}

.chat-input {
  display: flex;
  padding: 15px;
  border-top: 1px solid #e0e0e0;
}

.chat-input textarea {
  flex: 1;
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  margin-right: 12px;
  resize: vertical;
  transition: border-color 0.3s ease; /* 输入框边框颜色过渡动画 */
}

.chat-input textarea:focus {
  border-color: #007bff;
  outline: none;
  box-shadow: 0 0 8px rgba(0, 123, 255, 0.3);
}

.chat-input button {
  padding: 10px 15px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s ease; /* 发送按钮背景色过渡动画 */
}

.chat-input button:hover {
  background-color: #0056b3;
}

.chat-input textarea:disabled,
.chat-input button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

:deep(.deepThink) {
  color: darkgray !important;
}

.session-actions-trigger {
  cursor: pointer;
  font-size: 1.2em;
  color: #666;
  padding: 0 5px;
}

.session-actions-menu {
  position: absolute;
  top: 0;           /* 修改定位 */
  right: 40px;      /* 修改定位 */
  background-color: white;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 5px;
  z-index: 10;
}

.session-actions-menu button {
  display: block;
  width: 100%;
  padding: 5px 10px;
  background-color: transparent;
  border: none;
  cursor: pointer;
  text-align: left;
  transition: background-color 0.3s ease;
}

.session-actions-menu button:hover {
  background-color: #e8f6f8;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>